<template>
  <div style="margin-top: 5px;margin-bottom: 5px;margin-left: 10px" >
    <el-button type="primary" size="default" @click="refresh">刷新</el-button>
    <el-button type="primary" size="default" @click="addTopic">添加</el-button>
    <el-button type="danger" size="default" @click="deleteTopic">删除</el-button>
  </div>
  <div style="margin: 5px" v-loading="loading">
    <el-table :data="topics" border stripe v-loading @selection-change="selectionChange" :height="pageHeight-42" :default-sort="{ prop: 'status', order: 'descending' }">
      <el-table-column type="selection" width="40" />
      <el-table-column prop="serverName" label="MQ服务" width="200" sortable/>
      <el-table-column prop="groupName" label="组名称" width="200" sortable/>
      <el-table-column prop="topic" label="主题" width="200" sortable/>
      <el-table-column prop="tag" label="标签" width="200" sortable/>
      <el-table-column prop="status" label="状态" width="80" sortable :sort-by="['status','serverName']" >
        <template #default="scope" >
          <span v-show="scope.row.status" :style="{color:'green'}">已订阅</span>
          <span v-show="!scope.row.status" :style="{color:'red'}">未订阅</span>
        </template>
      </el-table-column>
      <el-table-column prop="note" label="说明" />
      <el-table-column fixed="right" label="操作" width="80">
        <template #default="scope">
          <el-button type="text" size="small" @click="listenTopic(scope.row)">{{ scope.row.status?"取消订阅":"订阅" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="dialogFormVisible" title="添加消息主题" width="25%" draggable @closed="closedDialog">
    <el-form ref="formref" :rules="rules" :model="form">
      <el-form-item label="MQ消息服务" :label-width="105" prop="serverName" required>
        <el-select v-model="form.serverName" placeholder="请选择MQ消息服务" style="width: 300px">
          <el-option v-for="server in servers" :label="server.name+'('+server.ip+':'+server.port+')'" :value="server.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="组名称" :label-width="105" prop="groupName" required>
        <el-input v-model="form.groupName" autocomplete="off" style=" width: 300px;" ></el-input>
      </el-form-item>
      <el-form-item label="主题" :label-width="105" prop="topic" required>
        <el-input v-model="form.topic" autocomplete="off" style=" width: 300px;" ></el-input>
      </el-form-item>
      <el-form-item label="标签" :label-width="105" prop="tag">
        <el-input v-model="form.tag" autocomplete="off" style=" width: 300px;" ></el-input>
      </el-form-item>
      <el-form-item label="说明" :label-width="105" prop="note">
        <el-input type="textarea" rows="2" v-model="form.note" autocomplete="off" style=" width: 300px;" ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog(false)">取消</el-button>
        <el-button type="primary" @click="closeDialog(true)"
        >添加</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {menuList_Setting} from "@/data/MenuList";

export default {
  name: "Topic",
  data(){
    return {
      servers:[],
      topics:[],
      dialogFormVisible:false,
      loading:false,
      selectRows:[],
      pageHeight:500,
      form: {
        groupName:"",
        topic:"",
        tag:"",
        note:"",
        serverName:""
      },
      rules: {
        serverName:[{
          required: true,
          message:"请输入MQ服务名称",
          trigger: "blur"
        }],
        groupName:[{
          required: true,
          message:"请输入组名称",
          trigger: "blur"
        }],
        topic:[{
          required: true,
          message:"请输入组名称",
          trigger: "blur"
        }]
      }
    }
  },
  methods:{
    getHeight(){
      this.pageHeight=window.innerHeight-30-42
    },
    saveTopic(){
      this.$axios.post(
        "/topic/add",
        {
          serverName:this.form.serverName,
          groupName:this.form.groupName.trim(),
          topic:this.form.topic.trim(),
          tag:this.form.tag.trim(),
          note:this.form.note.trim()
        }
      ).then((success)=>{
            if(success.status==200 && success.data){
              this.$message({
                message:"保存主题成功!",
                type: "success",
                duration:2000
              })
              this.dialogFormVisible = false
              this.refresh()
            }else{
              this.$message({
                message:"保存主题失败!",
                type: "error",
                duration:2000
              })
            }
          }
      ).catch(error=>
          this.$message({
            message:"保存主题失败!"+error.toString(),
            type: "error",
            duration:2000
          })
      )
    },
    refresh(){
      this.loading=true;
      this.topics=[]
      this.$axios.all(
          [
            this.remoteCall.call(null,"/server/list","get"),
            this.remoteCall.call(null,"/consume/list","get"),
            this.remoteCall.call(null,"/topic/list","get"),
          ]
      ).then(
          this.$axios.spread((loadServer,loadConsume,loadTopic)=>{
            if(loadServer.status=200 && loadServer.data){
              this.servers=[]
              loadServer.data.forEach((server)=> {
                this.servers.push({
                  name:server.name,
                  ip:server.ip,
                  port:server.port
                })
              })
              if(this.servers.length==0){
                this.$message({
                  message:"还没有添加MQ消息服务信息!",
                  type: "warning",
                  duration:2000
                })
              }
            }else{
              this.$message({
                message:"查询MQ服务地址失败!",
                type: "warning",
                duration:2000
              })
            }
            let consumes=[]
            if(loadConsume.status=200 && loadConsume.data){
              consumes=loadConsume.data
            }

            if(loadTopic.status==200 && loadTopic.data){
              this.topics=loadTopic.data
            }else{
              this.$message({
                message:"查询消息主题失败!",
                type: "error",
                duration:2000
              })
            }

            this.topics.forEach(topic=>{
              if(consumes.indexOf(topic.uuid)>=0){
                topic.status=true
              }else{
                topic.status=false
              }
            })
            this.loading=false
          })
      ).catch(error=>{
        this.$message({
          message:"加载Topic信息异常!"+error.toString(),
          type: "error",
          duration:2000
        })
      })
    },
    addTopic(){
      if(this.servers.length==0){
        this.$message({
          message:"请先添加MQ消息服务!",
          type: "error",
          duration:2000
        })
      }else {
        this.dialogFormVisible = true
      }
    },
    selectionChange(rows){
      this.selectRows=rows
    },
    remoteCall(url,type){
      if(type=="post") {
        return this.$axios.post(url)
      }else{
        return this.$axios.get(url)
      }
    },
    deleteTopic(){
      let apis=[]
      this.selectRows.forEach(topic=>{
        apis.push(
            this.remoteCall.call(null,"/topic/delete?uuid="+topic.uuid,"post")
        )
      })
      this.$axios.all(apis).then(this.$axios.spread((...results)=>{
        results.forEach(result=>{
          if(result.status!=200 || result.data!=true){
            this.$message({
              message:"删除消息主题失败!"+result.config.url,
              type: "error",
              duration:2000
            })
          }
        })
        this.refresh()
      })).catch(error=>{
        console.log(error)
      })
    },
    closeDialog(save){
      if(!save){
        this.dialogFormVisible=false
      }else{
        this.$refs["formref"].validate((valid) => {
          if (valid) {
            this.saveTopic()
          } else {
            this.$message({
              message:"存在非法信息！!",
              type: "error",
              duration:2000
            })
          }
        })
      }
    },
    closedDialog(){
      this.$refs["formref"].resetFields()

      this.$refs["formref"].clearValidate()
    },
    listenTopic(row){
      let url="/consume/start?uuid="+row.uuid
      let action="订阅"
      if (row.status){
        url="/consume/stop?uuid="+row.uuid
        action="取消订阅"
      }
      this.$axios.post(url).then( success=>{
        if(success.status=200 && success.data){
          this.$message({
            message:action+"主题成功!",
            type: "success",
            duration:2000
          })
          let index=-1
          this.topics.forEach((topic,i)=>{
            if(topic.uuid==row.uuid){
              index=i
            }
          })
          this.topics[index].status=!this.topics[index].status
          // this.$router.replace({path: "/consume"})
        }else{
          this.$message({
            message:action+"主题失败!",
            type: "warning",
            duration:2000
          })}
      }).catch(error=>{
        this.$message({
          message:action+"主题失败!"+error.toString(),
          type: "error",
          duration:2000
        })}
      )
    }
  },
  created() {
    window.addEventListener('resize', this.getHeight);
    this.getHeight()
    this.refresh()
  }
}
</script>

<style scoped>

</style>